import jpype


def runJava(rescoucePath, inOrder, prefix, suffixLength, exportPath):
    # Launch the JVM
    path1 = "jar/desktop-tools-1.0-SNAPSHOT.jar"
    path2 = "jar/spring-core-5.3.20.jar"
    path3 = "jar/fastjson-1.2.83.jar"
    path4 = "jar/commons-io-2.11.0.jar"
    jvmDefaultPath = jpype.getClassPath()
    # print(jvmDefaultPath)
    try:
        if not jpype.isJVMStarted():
            print('--------start jvm---------')
            jpype.startJVM(jvmDefaultPath,
                           # "jvm/bin/server/jvm.dll",
                           "-ea",
                           "-Dfile.encoding=utf-8",
                           classpath=[path1, path2, path3, path4]
                           )
        if not jpype.java.lang.Thread.isAttached():
            print('-----attaching jvm-----')
            jpype.attachThreadToJVM()
    except OSError as e:
        print("OSError: ", e)
        return {"error": 500, "msg": "发生错误"}
        # if e.__str__() == "JVM cannot be restarted" or e.__str__() == "JVM is already started":
        #     print("JVM已启动")
        #     pass
        # else:
        #     print("其他错误", e)
        #     return
    except Exception as e:
        print("Exception: ", e)
        return {"error": 500, "msg": "发生错误"}

    jpype.java.lang.System.out.println("---------已启动JVM---------")

    classmethod = jpype.JPackage("com.banmao.desktop_tools").RenameFiles()

    try:
        result = classmethod.renameFiles(rescoucePath, inOrder, prefix, suffixLength, exportPath)
        return result
        # print(result)
    except jpype.java.lang.IllegalArgumentException as e:
        print("调用Java代码发生异常", e, sep=": ")
        return {"error": 500, "msg": "错误，请联系管理员: \n" + e.__str__()}
    except Exception as e:
        print("Exception: ", e)
        return {"error": 500, "msg": "错误，请联系管理员: \n" + e.__str__()}

    # jpype.shutdownJVM()


if __name__ == "__main__":
    runJava(None, None, None, None, None)
